#include "comm.hpp"

int main()
{
    //与进程地址空间进行挂接
    int shmid = CreateShm();

    printf("key: 0x%x\n", Get_Key());
    printf("shmid: %d\n", shmid);
    std::cout << " attack start! " << std::endl;
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    if(shmaddr == (void*)-1)
    {
        perror("processa.cpp::main::shmaddr");
        return 1;
    }

    //打开文件，向文件中写入
    // int fd = open(PATHNAME_AGAIN, O_WRONLY | O_CREAT | O_APPEND, 0666);
    // if(fd < 0)
    // {
    //     perror("processa.cpp::main::open");
    //     return 1;
    // }

    //int cnt = 10;
    //向共享内存中写入数据
    while(true)
    {   

      //  printf("1\n");
        printf("processb say@ ");
        //直接往共享内存中写入数据
        fgets(shmaddr, SIZE, stdin);
    //     ssize_t s = write(Get_Shmid(), shmaddr, SIZE);
    //     if(s < 0)
    //     {
    //         perror("processa.cpp::main::write");
    //         break;
    //     }
    //     else if(s == 0)
    //     break;
    //    sleep(1);
   }
    // sleep(2);
    
    // printf("nxbw\n");

    std::cout << " attack end! " << std::endl;

    //切断该进程与共享内存的联系
    int n = shmdt(shmaddr);
    if(n < 0)
    {
        perror("processa.cpp::main::shmdt\n");
        return 1;
    }
    else
    {
        printf("Disassociation successful\n");
    }

    sleep(5);

    //释放共享内存
    n = shmctl(shmid, IPC_RMID, nullptr);
    if(n < 0)
    {
        std::cout << "return fail!" << std::endl;
        return 1;
    }
    else 
    {
        std::cout << "normal quit!" << std::endl;
    }

    

    return 0;
}